import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [{
        path: '/login',
        name: 'Login',
        component: () =>
            import ('@/views/login')
    },
    {
        path: '/',
        // name: 'layout', 
        component: () =>
            import ('@/views/layout'),
        children: [{
            // path为空 会作为默认子路由渲染
            path: '',
            name: 'home',
            component: () =>
                import ('@/views/home')
        }, {
            path: '/article',
            name: 'article',
            component: () =>
                import ('@/views/article')
        }, {
            path: '/publish',
            name: 'publish',
            component: () =>
                import ('@/views/publish')
        }, {
            path: '/image',
            name: 'image',
            component: () =>
                import ('@/views/image')
        }, {
            path: '/comment',
            name: 'comment',
            component: () =>
                import ('@/views/comment')
        }]
    }
]

const router = new VueRouter({
    routes
});

// 路由导航守卫
// to:要去的路由信息
// from:来自哪里的路由信息
router.beforeEach((to, from, next) => {
    const user = JSON.parse(window.localStorage.getItem('user'));
    if (to.path !== '/login') {
        if (user) {
            next();
        } else {
            next('/login');
        }
    } else {
        next();
    }
});

export default router